package com.muapet.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.muapet.model.Account;
import com.muapet.model.User;
import com.muapet.service.IUserService;
import com.muapet.util.Md5Utils;
import com.muapet.util.MyFileUpload;
import com.muapet.util.constants.MyConstants;

@Controller
@RequestMapping("/user")
public class UserController {

	private IUserService userService;

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@RequestMapping("/home")
	public ModelAndView home() {
		ModelAndView mav = new ModelAndView("index");
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST, path = "/login")
	public ModelAndView login(HttpServletRequest request, String loginname,
			String password) {
		User user = userService.login(loginname, Md5Utils.md5(password));
		if (user != null) {
			request.getSession().setAttribute("loginUser", user);
			ModelAndView mav = new ModelAndView("index");
			return mav;
		} else {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "密码错误，登录失败");
			return mav;
		}
	}

	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.invalidate();
		}
		return new ModelAndView("index");
	}

	@RequestMapping(method = RequestMethod.POST, path = "/add")
	public ModelAndView add(User user) {
		user.setPassword(Md5Utils.md5(user.getPassword()));
		user = userService.add(user);
		if (user != null && user.getId() != null) {
			ModelAndView mav = new ModelAndView("index");
			return mav;
		} else {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "注册失败");
			return mav;
		}
	}

	@RequestMapping(path = "/editSelf")
	public ModelAndView editSelf() {
		ModelAndView mav = new ModelAndView("editUser");
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST, path = "/update")
	public ModelAndView update(User user, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "请先登录");
			return mav;
		} else if (loginUser.getId().equals(user.getId())) {
			userService.update(user);
			user = userService.findById(user.getId());
			request.getSession().setAttribute("loginUser", user);
			return userInfo(user.getId(), request);
		} else {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "只能修改自己信息");
			return mav;
		}
	}

	@RequestMapping(path = "/updatePassword")
	public ModelAndView updatePassword(HttpServletRequest request) {
		ModelAndView mav;
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "请先登录");
			return mav;
		} else {
			mav = new ModelAndView("updatePassword");
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/updatePwd")
	@ResponseBody
	public String updatePwd(String password, String oldPassword,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String oldPwdMd5 = Md5Utils.md5(oldPassword);
		String PwdMd5 = Md5Utils.md5(password);
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请登录后重试！");
		} else {
			if (oldPassword != null
					&& loginUser.getPassword().equals(oldPwdMd5)) {
				userService.updatePwdByUserId(loginUser.getId(), PwdMd5);
				resultMap.put("msg", "success");
				HttpSession session = request.getSession();
				if (session != null) {
					session.invalidate();
				}
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "原密码不正确！");
			}
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/checkSameLoginname")
	@ResponseBody
	public String checkSameLoginname(String loginname) {
		Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
		resultMap.put("valid", userService.checkSameLoginname(loginname));
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(path = "/userInfo")
	public ModelAndView userInfo(Integer userId, HttpServletRequest request) {
		User user;
		ModelAndView mav;
		if (userId == null || userId <= 0) {
			User loginUser = (User) request.getSession().getAttribute(
					"loginUser");
			if (loginUser == null) {
				mav = new ModelAndView("error");
				mav.addObject("msg", "请先登录");
				return mav;
			} else {
				user = loginUser;
			}
		} else {
			user = userService.findShowUserById(userId);
		}
		if (user == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到用户");
		} else {
			mav = new ModelAndView("userBaseInfo");
			mav.addObject("user", user);
		}
		return mav;

	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/saveIcon")
	@ResponseBody
	public String saveIcon(MultipartFile userIcon, HttpServletRequest request) {
		String iconURL = new MyFileUpload().writeImg(userIcon,
				MyConstants.USER_ICON_BASE_URL);
		return JSON.toJSONString(iconURL);
	}

	@RequestMapping(path = "/myWallet")
	public ModelAndView myWallet(HttpServletRequest request) {
		ModelAndView mav;
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "请先登录");
			return mav;
		} else {
			Account account = userService
					.findAccountByUserId(loginUser.getId());
			if (account == null) {
				mav = new ModelAndView("newWallet");
			} else {
				mav = new ModelAndView("myWallet");
				mav.addObject("account", account);
			}
		}
		return mav;
	}

	@RequestMapping(path = "/updatePayPwd")
	public ModelAndView updatePayPwd(HttpServletRequest request) {
		ModelAndView mav;
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "请先登录");
			return mav;
		} else {
			mav = new ModelAndView("updatePayPwd");

		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/updateAccountPwd")
	@ResponseBody
	public String updateAccountPwd(String password, String oldPassword,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String oldPwdMd5 = Md5Utils.md5(oldPassword);
		String PwdMd5 = Md5Utils.md5(password);
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请登录后重试！");
		} else {
			Account account = userService
					.findAccountByUserId(loginUser.getId());
			if (account == null) {
				userService.updateAccountPwdByUserId(loginUser.getId(), PwdMd5);
				resultMap.put("msg", "success");
			} else if (oldPassword != null
					&& account.getPayPassword().equals(oldPwdMd5)) {
				userService.updateAccountPwdByUserId(loginUser.getId(), PwdMd5);
				resultMap.put("msg", "success");
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "原支付密码不正确！");
			}
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/updateAccount")
	@ResponseBody
	public String updateAccount(Double money, Boolean isAdd,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请登录后重试！");
		} else {
			Account account = userService
					.findAccountByUserId(loginUser.getId());
			if (account == null) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "找不到钱包信息，请刷新页面后重试！");
			} else if (isAdd != null && isAdd) {
				userService.updateAccountByUserId(loginUser.getId(), money,
						isAdd);
				resultMap.put("msg", "success");
			} else if (isAdd != null && !isAdd) {
				if (money > account.getBalance()) {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "余额不足！");
				} else {
					userService.updateAccountByUserId(loginUser.getId(), money,
							isAdd);
					resultMap.put("msg", "success");
				}

			}
		}
		return JSON.toJSONString(resultMap);
	}
}